#include "musiclist.h"

#include <QMimeDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include "music.h"

MusicList::MusicList()
{

}

void MusicList::addMusicsByUrl(QList<QUrl> &musicUrls)
{

    //将所以的音乐放置到musicList里面
    for (auto e : musicUrls)
    {
         bool flag = true;
        //检查要添加的文件是否是一个有效的歌曲文件
        //检查歌曲的MiME类型

        //文件重复的过滤
        //如果文件已经在musicList当中了,就不在添加
        //过滤方式: 将当前将要添加到musicList文件当中的路径,与musicList中已经存在的
        //的歌曲文件作比较,如果歌曲文件已经存在,在将其添加到歌曲列表中

        for (auto music : musicList)
        {
            if (music.getMusicUrl() == e)
            {
                flag = false;
            }
        }

        if (flag)
        {
            QMimeDatabase mineDB;
            QMimeType mineType = mineDB.mimeTypeForFile(e.toLocalFile());
            QString mime = mineType.name();
              //qDebug() << e << ":" << mime;

            //mine 和 audio/mepg(mp3) audio/flac(无损音乐) audio/wav
            if (mime == "audio/mpeg" || mime == "audio/flac" || mime == "audio/wav")
            {
                //qDebug() << e;
                // qDebug() << e << ":" << mime;
                Music music(e);
                musicList.push_back(music);
            }
        }

    }
}

MusicList::iterator MusicList::findMusicByMusicId(const QString &musicId)
{
    auto iter = begin();

    while (iter != end())
    {
        if ((*iter).getMusicId() == musicId)
        {
            return iter;
        }

        iter++;
    }

    return end();
}

MusicList::iterator MusicList::begin()
{
    return musicList.begin();
}

MusicList::const_iterator MusicList::begin() const
{
    return musicList.begin();
}

MusicList::iterator MusicList::end()
{
    return musicList.end();
}

MusicList::const_iterator MusicList::end() const
{
    return musicList.end();
}

void MusicList::writeToDB()
{
    for (auto music : musicList)
    {
        //拿到每一个music对象之后,将music的所以属性写入到数据库
        //具体写入单个Music对象的操作也封装成一个函数
        music.InsertMusicToDB();
    }
}

void MusicList::readToDB()
{
    QSqlQuery query;
    query.prepare("select musicId,musicName,musicSinger,musicAlbumn,musicUrl,duration,isLike,isHistory from MusicInfo");

    if (!query.exec())
    {
        qDebug() << "数据库查询失败: " << query.lastError().text();
        return;
    }

    while (query.next())
    {
        Music music;

        music.setMusicId(query.value(0).toString());
        music.setMusicName(query.value(1).toString());
        music.setMusicSinger(query.value(2).toString());
        music.setMusicAlbum(query.value(3).toString());
        music.setMusicUrl(query.value(4).toString());
        music.setMusicDuration(query.value(5).toLongLong());
        music.setIsLike(query.value(6).toBool());
        music.setIsHistory(query.value(7).toBool());

        musicList.push_back(music);
    }
}
